package org.zw.android.framework.http;

import java.io.InputStream;

import org.zw.android.framework.async.AsyncTaskHandler;

/**
 * File download callback
 * 
 * @author zhouwei
 *
 */
public abstract class DownloadCallback extends BaseFilter {
	
	public final String getUrl(){
		return getRequset() != null ? getRequset().getUrl() : null ;
	}
	
	public final long getLength(){
		return getResponseBean() != null ? getResponseBean().getLength() : 0 ;
	}
	
	@Override
	public final boolean doFilter(HttpRequest request, ResponseBean bean,HttpUIHandler uiHandler) {
		return true ;
	}
	
	protected final Object download(HttpRequest req ,ResponseBean bean,HttpUIHandler handler){
		
		attachUiHandler(handler);
		attachObject(req, bean);
		
		return callback(bean != null ? bean.getInputStream() : null);
	}
	
	public final void sendDownloadProgress(long total, int readed){
		
		AsyncTaskHandler handler = getHandler() ;
		
		if(handler instanceof HttpUIHandlerDownload){
			((HttpUIHandlerDownload)handler).sendDownloadProgress(getRequset(),total, readed);
		}
	}
	
	public HttpUIHandlerDownload getDownloadHandler(){
		
		AsyncTaskHandler handler = getHandler() ;
		
		if(handler instanceof HttpUIHandlerDownload){
			return (HttpUIHandlerDownload) handler;
		}
		
		return null ;
	}
	
	public abstract Object callback(InputStream input) ;
}
